<?php

namespace app\admin\controller\agent;

use app\admin\model\agent\Bill;
use app\admin\model\Githouse;
use app\admin\model\halt\Cate;
use app\admin\model\Preproduct;
use app\common\controller\Backend;
use app\common\model\Agent;
use app\common\model\order\Orderitem;
use think\Db;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Delivery extends Backend
{
    
    /**
     * Order模型对象
     * @var \app\admin\model\delivery\Order
     */
    protected $model = null;

    protected $searchFields = 'delivery_id';
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\delivery\Order;
        $this->view->assign("typeList", $this->model->getTypeList());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
//        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            $Githouselist = Githouse::select();
            $Githouselist = collection($Githouselist)->toArray();
            $Githouselist = array_column($Githouselist,'gname','id');
            foreach ($list as $row) {
                if($row->type == 2)
                {
                     $row['warehouse_text'] = Agent::AgentName($row->warehouse);
                }else{
                    $row['warehouse_text'] = $Githouselist[$row->warehouse];
                }
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function delGoods()
    {
        Db::transaction(function(){
            // 删除发货单。然后type =1 库存回滚 type = 2 价格回滚
            $delivery_id = $this->request->request('delivery_id');
            $deliver = $this->model->get($delivery_id);
            $deliveryData = Db::name('delivery_goods')->where(['delivery_id'=>$delivery_id])->select();
            if($deliver->type == 1)
            {
                //type = 2
                foreach ($deliveryData as $value)
                {
                    add_stock($deliver->warehouse,$value['product_id'],$value['number'],$this->auth->userid);
                }
            }
            if($deliver->type == 2)
            {
                $Agent = Agent::get($deliver->warehouse);//代理商ID
                $Agent->product_discount = unserialize($Agent->product_discount);
                $total = $this->total($deliveryData,$Agent);//发货单金额
                $Agent->deduction_amount -= $total;
                $Agent->allowField(['deduction_amount'])->save(['deduction_amount'=>$Agent->deduction_amount],$Agent->id);

                //添加一条记录
                Bill::create([
                    'order_id'=>$deliver->order_id,
                    'agent_id'=>$Agent->id,
                    'note'=>$this->auth->username.'调货作废',
                    'amount'=>$total,
                    'type'=>5,//作废
                    'status'=>3//作废
                ]);
            }
            $order = new \app\common\model\order\Order();
            $orderts = $order->get($deliver->order_id);

            if($orderts->deliverystatus != 2)
            {
                $orderts->deliverystatus = 2;//发货完成
                $orderts->save();//发货完成
            }
            $deliver->status = 0;
            $deliver->save();

        });
        $this->success('操作完成！');
    }

    /**
     * 返回发货的金额
     * @param $deliveryData
     * @param $Agent
     * @return float|int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function total($deliveryData,$Agent)
    {
        $product = array_column($deliveryData,'number','product_id');
        //获取所有商品的价格 跟分类
        $total = 0;
        $productData = Preproduct::where(['id'=>['in',implode(',',array_column($deliveryData,'product_id'))]])->field('id,class_text,cname,classif,price,ctime')->select();
        foreach ($productData as &$value)
        {
            $dis = explode(',',$value['class_text']);
            foreach ($Agent->product_discount as $key=>$values)
            {
                $value['discount_price'] = 0;
                if(in_array($value['classif'],$dis) || $value['classif'] == $values['id'])
                {
                    $value['discount_price'] = $value['price'] * ($values['discount'] / 10);//折扣后价格
                }
            }
            $total += $product[$value['id']] * $value['discount_price'];
        }
        return $total;
    }


}
